import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/r.dart';
import 'package:sinosheets/components/NetWorkImage/NetworkImageWidget.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';

import 'logic.dart';

class ShoppingPage extends StatefulWidget {
  ShoppingPage({Key? key}) : super(key: key);

  @override
  State<ShoppingPage> createState() => _ShoppingPageState();
}

class _ShoppingPageState extends State<ShoppingPage> with AutomaticKeepAliveClientMixin {
  final ShoppingLogic logic = Get.put(ShoppingLogic());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<ShoppingLogic>(builder: (get) {
      return Scaffold(
        backgroundColor: const Color(0xFFF7F8FA),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Image.asset(
            R.assetsImgSinosheets,
            width: 150.r,
            fit: BoxFit.fill,
          ),
          centerTitle: true,
        ),
        body: get.isLoading
            ? const Center(child: CircularProgressIndicator())
            : SafeArea(
                child: EasyRefresh(
                    controller: get.controller,
                    onRefresh: get.onRefresh,
                    child: ListView(
                      children: [
                        // 搜索框
                        _buildSearchBar(get),

                        // 海报区域
                        _buildBanner(),

                        // 图标导航区域
                        _buildCategoryIcons(get),

                        //热门分类区域
                        _buildHotCategory(get),

                        // 双列图片展示
                        _buildTwoColumnImages(get),
                        SizedBox(height: 20.r),

                        // 商品美化图片区域
                        _buildBeautyProducts(get),

                        // 商品列表
                        _buildProductList(get),
                      ],
                    ))),
      );
    });
  }

  /// 构建搜索框
  Widget _buildSearchBar(ShoppingLogic get) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.r, vertical: 8.r),
      height: 56.r,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(28.r),
        border: Border.all(
          color: const Color(0xFFE0E0E0),
          width: 1.5.r,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16.r,
            offset: Offset(0, 6.r),
            spreadRadius: 0,
          ),
          BoxShadow(
            color: Colors.white,
            blurRadius: 0,
            offset: Offset(0, 1.r),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Row(
        children: [
          SizedBox(width: 20.r),
          // 搜索图标
          Container(
            width: 36.r,
            height: 36.r,
            decoration: BoxDecoration(
              color: ColorUtils.themeColor,
              borderRadius: BorderRadius.circular(18.r),
              boxShadow: [
                BoxShadow(
                  color: ColorUtils.themeColor.withOpacity(0.3),
                  blurRadius: 8.r,
                  offset: Offset(0, 2.r),
                ),
              ],
            ),
            child: const Icon(
              Icons.search,
              color: Colors.white,
              size: 18,
            ),
          ),
          SizedBox(width: 16.r),
          // 输入框
          Expanded(
            child: TextField(
              controller: get.searchController,
              decoration: const InputDecoration(
                border: InputBorder.none,
                hintText: 'Search by name, link or ID',
                hintStyle: TextStyle(
                  color: Color(0xFFBDBDBD),
                  fontSize: 16,
                  fontWeight: FontWeight.w400,
                ),
                contentPadding: EdgeInsets.symmetric(vertical: 16),
              ),
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF424242),
              ),
              onSubmitted: (value) => get.onSearchClick(),
            ),
          ),
          // 清除按钮
          if (get.searchController.text.isNotEmpty)
            Container(
              margin: EdgeInsets.only(right: 12.r),
              child: GestureDetector(
                onTap: () {
                  get.searchController.clear();
                  get.update();
                },
                child: Container(
                  width: 28.r,
                  height: 28.r,
                  decoration: BoxDecoration(
                    color: const Color(0xFFF5F5F5),
                    borderRadius: BorderRadius.circular(14.r),
                    border: Border.all(
                      color: const Color(0xFFE0E0E0),
                      width: 1.r,
                    ),
                  ),
                  child: const Icon(
                    Icons.close,
                    color: Color(0xFF757575),
                    size: 16,
                  ),
                ),
              ),
            ),
          // 搜索按钮
          Container(
            margin: EdgeInsets.only(right: 8.r),
            child: GestureDetector(
              onTap: () {
                get.onSearchClick();
              },
              child: Container(
                width: 44.r,
                height: 44.r,
                decoration: BoxDecoration(
                  color: ColorUtils.themeColor,
                  borderRadius: BorderRadius.circular(22.r),
                  boxShadow: [
                    BoxShadow(
                      color: ColorUtils.themeColor.withOpacity(0.4),
                      blurRadius: 12.r,
                      offset: Offset(0, 4.r),
                    ),
                  ],
                ),
                child: const Icon(
                  Icons.arrow_forward,
                  color: Colors.white,
                  size: 20,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建海报区域
  Widget _buildBanner() {
    return Container(
      height: 160.r,
      margin: EdgeInsets.symmetric(horizontal: 10.r, vertical: 10.r),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha(10),
            blurRadius: 12.r,
            offset: Offset(0, 4.r),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: Swiper(
          itemCount: 1,
          autoplay: true,
          loop: true,
          duration: 1000,
          pagination: const SwiperPagination(
            alignment: Alignment.bottomCenter,
            builder: SwiperPagination.dots,
          ),
          itemBuilder: (BuildContext context, int index) {
            return Image.asset(
              R.assetsImgSummer,
              fit: BoxFit.cover,
            );
          },
        ),
      ),
    );
  }

  /// 构建分类图标区域
  Widget _buildCategoryIcons(ShoppingLogic get) {
    if (get.isValidateCode) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.r),
        margin: EdgeInsets.only(top: get.categoryList.isEmpty ? 0 : 10.r, bottom: get.categoryList.isEmpty ? 0 : 20.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: get.categoryIcons.asMap().entries.map((entry) {
            int index = entry.key;
            Map<String, dynamic> category = entry.value;
            return _buildCategoryIcon(category, index, get);
          }).toList(),
        ),
      );
    } else {
      ///从商品中随机取3个
      List productList = get.otherProductList.take(3).toList();
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.r),
        margin: EdgeInsets.only(top: get.categoryList.isEmpty ? 0 : 10.r, bottom: get.categoryList.isEmpty ? 0 : 20.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: productList.asMap().entries.map((entry) {
            int index = entry.key;
            Map product = entry.value;
            return _buildCateProductIcon(product, index, get);
          }).toList(),
        ),
      );
    }
  }

  Widget _buildCategoryIcon(Map<String, dynamic> category, int index, ShoppingLogic get) {
    return GestureDetector(
      onTap: () => get.onCategoryTap(index),
      child: Column(
        children: [
          Container(
            width: 60.r,
            height: 60.r,
            decoration: BoxDecoration(
              color: category['color'],
              borderRadius: BorderRadius.circular(30.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8.r,
                  offset: Offset(0, 2.r),
                ),
              ],
            ),
            child: Icon(
              category['icon'],
              color: category['iconColor'],
              size: 28.r,
            ),
          ),
          SizedBox(height: 8.r),
          Text(
            category['name'],
            style: TextStyle(
              fontSize: 14.r,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCateProductIcon(Map product, int index, ShoppingLogic get) {
    return GestureDetector(
      onTap: () {
        RouteUtils.toProductDetail(product);
      },
      child: Container(
        width: 60.r,
        height: 60.r,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(30.r),
          border: Border.all(
            color: ColorUtils.themeColor,
            width: 1.r,
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(30.r),
          child: NetworkImageWidget(url: product['img'], fit: BoxFit.cover, width: 50.r, height: 50.r),
        ),
      ),
    );
  }

  /// 构建热门分类区域
  Widget _buildHotCategory(ShoppingLogic get) {
    return Container(
      margin: EdgeInsets.only(top: get.categoryList.isEmpty ? 0 : 10.r, bottom: get.categoryList.isEmpty ? 0 : 20.r),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: get.categoryList.map((category) {
          return GestureDetector(
            onTap: () {
              if (get.isValidateCode) {
                RouteUtils.toCategoryProduct(categoryId: "${category['id']}", categoryName: category['name']);
              } else {
                RouteUtils.toNoemalCategoryPList("${category['id']}", category['name']);
              }
            },
            child: SizedBox(
              width: ScreenUtil().screenWidth * 0.2,
              height: 80.r,
              child: Column(
                children: [
                  NetworkImageWidget(
                    url: category['img'],
                    fit: BoxFit.cover,
                    width: 50.r,
                    height: 50.r,
                  ),
                  SizedBox(height: 5.r),
                  Text(
                    category['name'] ?? '',
                    style: TextStyle(fontSize: 12.r, color: Colors.black87),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建双列图片展示
  Widget _buildTwoColumnImages(ShoppingLogic get) {
    if (get.doubleColumnImageList.isEmpty) {
      return SizedBox();
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.r),
      child: Row(
        children: [
          Expanded(
            child: _buildBeautyCard(get.doubleColumnImageList[0], get, height: 100.r),
          ),
          SizedBox(width: 12.r),
          Expanded(
            child: _buildBeautyCard(get.doubleColumnImageList[1], get, height: 100.r),
          ),
        ],
      ),
    );
  }

  /// 构建商品美化图片区域
  Widget _buildBeautyProducts(ShoppingLogic get) {
    if (get.beautyProductList.isEmpty) {
      return SizedBox();
    }

    return Container(
      color: Colors.orange.withOpacity(0.1),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 15.r),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.r),
            child: _buildFlexibleGrid(get.beautyProductList.cast<Map<String, dynamic>>(), get),
          ),
          SizedBox(height: 15.r),
        ],
      ),
    );
  }

  /// 构建灵活网格布局
  Widget _buildFlexibleGrid(List<Map<String, dynamic>> products, ShoppingLogic get) {
    if (products.isEmpty) return const SizedBox.shrink();
    return Column(
      children: [
        _buildBeautyCard(products[0], get, height: 150.r),
        SizedBox(height: 5.r),
        Row(
          children: [
            Expanded(child: _buildBeautyCard(products[1], get, height: 100.r)),
            SizedBox(width: 12.r),
            Expanded(child: _buildBeautyCard(products[2], get, height: 100.r)),
          ],
        ),
        SizedBox(height: 5.r),
        Row(
          children: [
            Expanded(child: _buildBeautyCard(products[3], get, height: 100.r)),
            SizedBox(width: 12.r),
            Expanded(child: _buildBeautyCard(products[4], get, height: 100.r)),
            SizedBox(width: 12.r),
            Expanded(child: _buildBeautyCard(products[5], get, height: 100.r)),
          ],
        ),
      ],
    );
  }

  /// 构建美化商品卡片
  Widget _buildBeautyCard(Map<String, dynamic> product, ShoppingLogic get, {double height = 150}) {
    return GestureDetector(
      onTap: () {
        RouteUtils.toProductDetail(product);
      },
      child: Container(
        height: height,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8.r,
              offset: Offset(0, 2.r),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              Positioned.fill(
                child: NetworkImageWidget(
                  url: product['img'],
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 10.r, vertical: 5.r),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.transparent,
                        Colors.black.withOpacity(0.7),
                      ],
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${product['price']}${product['symbol']}',
                        style: TextStyle(
                          color: Color(0xFFFF7D00),
                          fontSize: 12.r,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      if (product['crossedPrice'] != product['price'])
                        Column(
                          children: [
                            SizedBox(height: 2.r),
                            Text(
                              '${product['crossedPrice']}${product['symbol']}',
                              style: TextStyle(
                                color: Colors.white70,
                                fontSize: 10.r,
                                decoration: TextDecoration.lineThrough,
                              ),
                            )
                          ],
                        ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建商品列表
  Widget _buildProductList(ShoppingLogic get) {
    if (get.otherProductList.isEmpty) {
      return SizedBox();
    }

    return Container(
      color: Colors.pink.withOpacity(0.1),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 15.r),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.r),
            child: Text(
              'Products',
              style: TextStyle(
                fontSize: 18.r,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ),
          SizedBox(height: 16.r),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 16.r),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 16.r,
              crossAxisSpacing: 16.r,
              childAspectRatio: 0.65,
            ),
            itemCount: get.otherProductList.length,
            itemBuilder: (context, index) {
              return _buildProductCard(get.otherProductList[index], get);
            },
          ),
        ],
      ),
    );
  }

  /// 构建商品卡片
  Widget _buildProductCard(Map<String, dynamic> product, ShoppingLogic get) {
    return GestureDetector(
      onTap: () {
        RouteUtils.toProductDetail(product);
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8.r,
              offset: Offset(0, 2.r),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Center(
              child: ClipRRect(
                borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                child: NetworkImageWidget(
                  url: product['img'],
                  width: double.infinity,
                  height: 160.r,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Padding(
                padding: EdgeInsets.symmetric(horizontal: 10.r),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 12.r),
                    Text(
                      product['itemName'] ?? '',
                      style: TextStyle(fontSize: 13.r, color: Color(0xFF333333)),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.r),
                    Row(
                      children: [
                        Text('${product['price']} ${product['symbol']}', style: TextStyle(color: Color(0xFFFF7D00), fontSize: 14.r, fontWeight: FontWeight.bold)),
                        if (product['crossedPrice'] != product['price'])
                          Row(
                            children: [
                              SizedBox(width: 6.r),
                              Text('${product['crossedPrice']} ${product['symbol']}', style: TextStyle(color: ColorUtils.c_666666, fontSize: 10.r, decoration: TextDecoration.lineThrough)),
                            ],
                          )
                      ],
                    ),
                    SizedBox(height: 10.r),
                  ],
                ))
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    Get.delete<ShoppingLogic>();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
